﻿using GCC.Container.Abstracts;

using System;
using System.Collections.Generic;
using System.DeviceServer.Models;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.DeviceServer
{
    public class DeviceCache
    {

        public static DeviceCache Instance = new();
        public AbsGCCContext _context;
        private DeviceCache()
        {

        }

        
        public void Init(AbsGCCContext context)
        { 
           _context = context;
        }
        public async Task<List<DevType>> GetAllDevType()
        {
            CacheItemSettings cacheSett = new CacheItemSettings();
            cacheSett.SaveToAll = true;
           return await this._context.GetOrSet<List<DevType>>("allDevType", () =>
            {
                return Task.Run(() =>
                {
                    var dbres = AbsEntrance.DBManager!.LocalDB!.Select<DevType>().ToList();
                    return dbres;
                });
            }, cacheSett);
        }

        public async Task<List<DevParam>> GetAllDevParams()
        {
            CacheItemSettings cacheSett = new CacheItemSettings();
            cacheSett.SaveToAll = true;
            return await this._context.GetOrSet<List<DevParam>>("DevParams", () =>
            {
                return Task.Run(() =>
                {
                    var dbres = AbsEntrance.DBManager!.LocalDB!.Select<DevParam>().ToList();
                    return dbres;
                });
            }, cacheSett);
        }

        public async Task<string> getDevType()
        {
            Console.WriteLine("lsltest getDevType");
            var dbres = AbsEntrance.DBManager!.LocalDB!.Select<DevType>()
                .ToList();

            List<DeviceTypeJson> deviceTypeList = new List<DeviceTypeJson>();
            foreach (var item in dbres)
            {
                DeviceTypeJson temp = new DeviceTypeJson();
                temp.TypeID = item.TypeID.ToString();
                temp.TypeName = item.TypeName;
                temp.TypeICON = item.TypeICON.ToString();
                temp.PointName = item.PointName;
                deviceTypeList.Add(temp);
            }
            var res = System.Text.Json.JsonSerializer.Serialize<List<DeviceTypeJson>>(deviceTypeList);
            CacheItemSettings cacheSett = new CacheItemSettings();
            cacheSett.SaveToAll = true;
            await _context.Set<string>("DevType", res, cacheSett);
            return res;
        }
    }
}
